using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class LaserReceiverHandler : LightRayHandler {

	public GameObject objectToColor;
	public GameObject colorPicker;
	public Texture2D shadowTexture;
	
	private float pickerActiveTime;
	private float receiverActiveTime;
	
	
	private bool isActivated = true;
	private Dictionary<Color,float> listColors = new Dictionary<Color, float>();
	private List<Color> toRemove = new List<Color>();
	
	public override void initialize(int id, Vector3 position, float rotation, Color c, bool fixedObj){
		Type = ObjectType.LaserReceiver;
		
		base.initialize(id, position, rotation, c, fixedObj);
		colorPicker.GetComponent<ColorPickerHandler>().colorObject(c);
		
		LevelConstants.nbReceivers++;
		LevelConstants.nbActivatedReceivers++;
		
		deactivateObject();	
		
		if(!isFixed){
			colorPicker.SetActive(true);
			pickerActiveTime = Time.time;
		}
	}
	
	public override List<LightHitInfo> getNextLightRay(LightHitInfo hitInfo){
		List<LightHitInfo> newRays = new List<LightHitInfo>();
		
		if(listColors.ContainsKey(hitInfo.LightColor)){
			listColors[hitInfo.LightColor] = Time.time;
		}else{
			listColors.Add(hitInfo.LightColor, Time.time);
		}
		
		newRays.Add(hitInfo);
		
		return newRays;	
	}
	
	public override void FixedUpdate(){
		if(Time.time - pickerActiveTime > 3){
			colorPicker.SetActive(false);	
		}	
		
	}
	
	public void activateObject(){
		foreach(Transform child in objectToColor.transform){
			if(child.renderer != null){
				child.renderer.material.SetTexture("_MainTex",null);
			}
		}
		
		objectToColor.particleSystem.Play();
			
		LevelConstants.nbActivatedReceivers++;
		
		isActivated = true;
	}
	
	public void deactivateObject(){
		foreach(Transform child in objectToColor.transform){
			if(child.renderer != null){
				child.renderer.material.SetTexture("_MainTex",shadowTexture);
			}
		}
		
		objectToColor.particleSystem.Stop();
		objectToColor.particleSystem.Clear();
		
		LevelConstants.nbActivatedReceivers--;
		
		isActivated = false;
	}
	
	void LateUpdate(){
		toRemove.Clear();
		
		foreach(KeyValuePair<Color,float> entry in listColors){
			if(Time.time - entry.Value > 0.1){
				toRemove.Add(entry.Key);
			}
		}
		
		foreach(Color c in toRemove){
			listColors.Remove(c);	
		}
		
		if(listColors.Count != 0){
			Color mix = ColorUtils.addColors(listColors.Keys.ToArray());
			
			if(ColorUtils.equalsIgnoreAlpha(mix,currentColor)){
				if(!isActivated){
					activateObject();	
				}
			}else{
				if(isActivated){
					deactivateObject();	
				}	
			}
		}else{
			if(isActivated){
				deactivateObject();	
			}
		}
	}
	
	void OnDestroy(){
		if(isActivated){
			LevelConstants.nbActivatedReceivers--;	
		}
		LevelConstants.nbReceivers--;
	}
	
}
